//
//  CutoutCollageView.swift
//  SwiftPhtotEdit
//
//  Created by aw031 on 13/10/2025.
//

import UIKit

public typealias ClickBlock = () -> Void

public typealias ImageBlock = (_ image: UIImage?) -> Void

class CutoutCollageView: UIView , UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
    // MARK: - IBOutlets
    @IBOutlet weak var imageBgV: UIView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var autoCutBtn: UIButton!
    @IBOutlet weak var lassoCutBtn: UIButton!
    @IBOutlet weak var eraseBtn: UIButton!
    @IBOutlet weak var autoCutImgView: UIImageView!
    @IBOutlet weak var lassoCutImgView: UIImageView!
    @IBOutlet weak var eraseImgView: UIImageView!
    @IBOutlet weak var autoCutLabel: UILabel!
    @IBOutlet weak var lassoCutLabel: UILabel!
    @IBOutlet weak var eraseLabel: UILabel!
    

    
    // MARK: - Properties
    var erasePath: UIBezierPath?
    var undoStack: [UIBezierPath] = []
    var restoreStack: [UIBezierPath] = []
    var originalMask: UIImage?
    var sourceImage: UIImage?
    var lastTouchPoint: CGPoint = .zero
    var eraserIconView: UIImageView?
    var cutImage: UIImage?
    
    var isRestoring: Bool = false
    var isEdit: Bool = false
    var taskCount: Int = 0
    
    var isPinching: Bool = false
    
    
      // 闭包属性
      var backBtnClick: ClickBlock?
      var saveBtnClick: ImageBlock?
      
      // 需要获取当前视图控制器
      weak var viewController: UIViewController?
      
    
    // MARK: - Initialization
     override func awakeFromNib() {
         super.awakeFromNib()
         
         // 开启用户交互
         self.imageView.isUserInteractionEnabled = true

         // 添加捏合手势
         let pinch = UIPinchGestureRecognizer(target: self, action: #selector(handlePinch(_:)))
         self.imageView.addGestureRecognizer(pinch)

         // 添加拖拽手势（仅支持双指平移）
         let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:)))
         pan.minimumNumberOfTouches = 2
         pan.maximumNumberOfTouches = 2
         self.imageView.addGestureRecognizer(pan)
     }
     
     func setImage(_ image: UIImage) {
         self.sourceImage = image
         self.imageView.image = image
         
         self.autocutBtnClick(self.autoCutBtn)
     }
     
     // MARK: - Button Actions
     @IBAction func autocutBtnClick(_ sender: UIButton) {
         sender.isSelected = !sender.isSelected
         
         lassoCutBtn.isSelected = false
         eraseBtn.isSelected = false
         isEdit = false
         if let eraserIconView = self.eraserIconView {
             eraserIconView.isHidden = true
         }

         autoCutImgView.image = UIImage(named: sender.isSelected ? "make_autocut_sel" : "make_autocut_nor")
         lassoCutImgView.image = UIImage(named: "make_lassocut_nor")
         eraseImgView.image = UIImage(named: "make_erase_nor")
//
//         autoCutLabel.textColor = UIColor(hexString: sender.isSelected ? "#9684FF" : "#141415")
//         lassoCutLabel.textColor = UIColor(hexString: "#141415")
//         eraseLabel.textColor = UIColor(hexString: "#141415")

         if sender.isSelected {
             if let cutImage = self.cutImage {
                 self.imageView.image = cutImage
                 self.originalMask = cutImage
                 
                 self.resetTouchData()
             } else {
                 self.loadResultData(self.sourceImage)
             }
         } else {
             self.imageView.image = self.sourceImage
             self.originalMask = self.sourceImage
             
             self.resetTouchData()
         }
     }
     
     @IBAction func lassoCutBtnClick(_ sender: UIButton) {
         sender.isSelected = !sender.isSelected
         eraseBtn.isSelected = false
         isEdit = sender.isSelected
         
         if let eraserIconView = self.eraserIconView {
             eraserIconView.isHidden = !sender.isSelected
         }

//         lassoCutImgView.image = UIImage(named: sender.isSelected ? "make_lassocut_sel" : "make_lassocut_nor")
//         eraseImgView.image = UIImage(named: "make_erase_nor")
//         lassoCutLabel.textColor = UIColor(hexString: sender.isSelected ? "#9684FF" : "#141415")
//         eraseLabel.textColor = UIColor(hexString: "#141415")

         if !sender.isSelected { return }

         self.isRestoring = true
         self.originalMask = self.imageView.image

         if self.eraserIconView == nil {
             self.eraserIconView = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
             self.eraserIconView?.image = UIImage(named: "make_cut_line")
             self.eraserIconView?.center = self.imageView.center
             if let eraserIconView = self.eraserIconView {
                 self.imageView.addSubview(eraserIconView)
             }
         }
     }
     
     @IBAction func eraseBtnClick(_ sender: UIButton) {
         sender.isSelected = !sender.isSelected
         lassoCutBtn.isSelected = false
         isEdit = sender.isSelected
         
         if let eraserIconView = self.eraserIconView {
             eraserIconView.isHidden = !sender.isSelected
         }

         lassoCutImgView.image = UIImage(named: "make_lassocut_nor")
         eraseImgView.image = UIImage(named: sender.isSelected ? "make_erase_sel" : "make_erase_nor")
//         lassoCutLabel.textColor = UIColor(hexString: "#141415")
//         eraseLabel.textColor = UIColor(hexString: sender.isSelected ? "#9684FF" : "#141415")

         if !sender.isSelected { return }

         self.isRestoring = false
         self.originalMask = self.imageView.image

         if self.eraserIconView == nil {
             self.eraserIconView = UIImageView(frame: CGRect(x: 0, y: 0, width: 10, height: 10))
             self.eraserIconView?.image = UIImage(named: "make_cut_line")
             self.eraserIconView?.center = self.imageView.center
             if let eraserIconView = self.eraserIconView {
                 self.imageView.addSubview(eraserIconView)
             }
         }
     }
     
     @IBAction func backBtnClick(_ sender: UIButton) {
         self.removeFromSuperview()
         
         self.backBtnClick?()
     }
     
     @IBAction func saveBtnClick(_ sender: UIButton) {
         // 注意：这里需要替换为实际的 PurchaseManager 和 CommonClass 实现
         /*
         if !PurchaseManager.shared.isMember && CommonClass.showCutout() {
             let vc = PremiumEditionController()
             if let currentVC = CommonClass.currentViewController() {
                 currentVC.navigationController?.pushViewController(vc, animated: true)
             }
         } else {
             if self.imageView.image != nil {
                 CommonClass.updateCutout(true)
             }
             
             self.saveBtnClick?(self.imageView.image)
         }
         */
         
         // 临时实现 - 直接保存
         self.saveBtnClick?(self.imageView.image)
     }
     
     // MARK: - Touch Handling
     override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
         if !isEdit || isPinching { return }

         guard let touch = touches.first else { return }
         let touchPointInView = touch.location(in: self.imageView)

         guard let img = self.sourceImage else { return }

         let imageSize = img.size
         let imageViewSize = self.imageView.bounds.size
         let scale = min(imageViewSize.width / imageSize.width, imageViewSize.height / imageSize.height)
         let fittedImageSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
         let x = (imageViewSize.width - fittedImageSize.width) / 2.0
         let y = (imageViewSize.height - fittedImageSize.height) / 2.0

         let currentPoint = CGPoint(
             x: (touchPointInView.x - x) * (imageSize.width / fittedImageSize.width),
             y: (touchPointInView.y - y) * (imageSize.height / fittedImageSize.height)
         )

         if let eraserIconView = self.eraserIconView {
             eraserIconView.center = touchPointInView
         }

         guard let originalMask = self.originalMask else { return }

         if self.erasePath == nil {
             self.erasePath = UIBezierPath()
             self.erasePath?.lineWidth = 5.0
             self.erasePath?.lineCapStyle = .round
         }

         if self.lastTouchPoint == .zero {
             self.erasePath?.move(to: currentPoint)
         } else {
             let midPoint = CGPoint(
                 x: (self.lastTouchPoint.x + currentPoint.x) / 2.0,
                 y: (self.lastTouchPoint.y + currentPoint.y) / 2.0
             )
             self.erasePath?.addQuadCurve(to: midPoint, controlPoint: self.lastTouchPoint)
         }

         self.lastTouchPoint = currentPoint

         self.renderMask()
     }
     
     override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
         if !isEdit || isPinching { return }

         if let erasePath = self.erasePath, !erasePath.isEmpty {
             if self.isRestoring {
                 if self.restoreStack.isEmpty {
                     self.restoreStack = []
                 }
                 self.restoreStack.append(erasePath.copy() as! UIBezierPath)
                 // 恢复操作，清除擦除轨迹
                 self.undoStack.removeAll()
             } else {
                 if self.undoStack.isEmpty {
                     self.undoStack = []
                 }
                 self.undoStack.append(erasePath.copy() as! UIBezierPath)
                 // 擦除操作，清除恢复轨迹
                 self.restoreStack.removeAll()
             }
         }
         self.erasePath = nil
         self.lastTouchPoint = .zero
     }
     
     // MARK: - Mask Rendering
     func renderMask() {
         guard let sourceImage = self.sourceImage else { return }
         
         UIGraphicsBeginImageContextWithOptions(sourceImage.size, false, 0)
         defer { UIGraphicsEndImageContext() }
         
         self.originalMask?.draw(at: .zero)

         guard let ctx = UIGraphicsGetCurrentContext() else { return }
         ctx.saveGState()

         ctx.setLineCap(.round)
         ctx.setLineWidth(20.0)

         if self.isRestoring {
             for path in self.restoreStack {
                 ctx.saveGState()
                 ctx.addPath(path.cgPath)
                 ctx.replacePathWithStrokedPath()
                 ctx.clip()
                 sourceImage.draw(at: .zero)
                 ctx.restoreGState()
             }
             if let erasePath = self.erasePath {
                 ctx.saveGState()
                 ctx.addPath(erasePath.cgPath)
                 ctx.replacePathWithStrokedPath()
                 ctx.clip()
                 sourceImage.draw(at: .zero)
                 ctx.restoreGState()
             }
         } else {
             ctx.setBlendMode(.clear)
             ctx.setStrokeColor(UIColor.clear.cgColor)
             let paths = self.undoStack
             for path in paths {
                 ctx.addPath(path.cgPath)
                 ctx.strokePath()
             }
             if let erasePath = self.erasePath {
                 ctx.addPath(erasePath.cgPath)
                 ctx.strokePath()
             }
         }

         ctx.restoreGState()

         if let result = UIGraphicsGetImageFromCurrentImageContext() {
             self.imageView.image = result
             self.originalMask = result
         }
     }
     
     func resetTouchData() {
         self.undoStack.removeAll()
         self.restoreStack.removeAll()
         self.erasePath = nil
         self.lastTouchPoint = .zero
     }
     
     // MARK: - Album
     func albumClickEvent() {
         // 需要实现权限检查和相册访问
         /*
         PermissionManager.checkPhotoLibraryPermission()
         let imagePickerController = UIImagePickerController()
         imagePickerController.delegate = self
         imagePickerController.allowsEditing = false
         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
             imagePickerController.sourceType = .photoLibrary
             self.viewController?.present(imagePickerController, animated: true)
         }
         */
     }
     
     // MARK: - UIImagePickerControllerDelegate
     func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
         picker.dismiss(animated: true)
         
         if let vc = self.viewController {
             vc.navigationController?.popViewController(animated: true)
         }
     }
     
     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
         picker.dismiss(animated: true)
         if let image = info[.originalImage] as? UIImage {
             self.sourceImage = image
             self.imageView.image = image
             self.autocutBtnClick(self.autoCutBtn)
         }
     }
     
     // MARK: - Network Requests
     func loadResultData(_ image: UIImage?) {
         guard let image = image else {
             // PSProgressHUD.showToast("The image cannot be empty", view: self)
             return
         }
         
         // PSProgressHUD.show(in: self)
         
         // 需要实现网络请求逻辑
         /*
         let request = UploadImageRequest()
         request.image = image
         
         request.startWithCompletionBlock(success: { [weak self] request in
             guard let self = self else { return }
             if let responseDict = request.responseObject as? [String: Any],
                let code = responseDict["code"] as? NSNumber, code == 0,
                let data = responseDict["data"] as? [String: Any],
                let filePath = data["filePath"] as? String {
                 self.createTask(filePath)
             } else {
                 // PSProgressHUD.hide(in: self)
                 // PSProgressHUD.showToast("Please try again later", view: self)
             }
         }, failure: { [weak self] request, message in
             guard let self = self else { return }
             // PSProgressHUD.hide(in: self)
             // PSProgressHUD.showToast("Please try again later", view: self)
         })
         */
     }
     
     func createTask(_ filePath: String) {
         // 实现创建任务的网络请求
     }
     
     func taskStatus(_ taskId: String) {
         // 实现任务状态查询的网络请求
     }
     
     // MARK: - Gesture Handlers
     @objc func handlePinch(_ pinch: UIPinchGestureRecognizer) {
         switch pinch.state {
         case .began, .changed:
             self.isPinching = true
         case .ended, .cancelled:
             self.isPinching = false
         default:
             break
         }
         
         // 在当前 transform 上叠加缩放
         if let view = pinch.view {
             view.transform = view.transform.scaledBy(x: pinch.scale, y: pinch.scale)
         }
         pinch.scale = 1.0 // 重置 scale，避免叠加过度
         
         self.resetTouchData()
     }
     
     @objc func handlePan(_ pan: UIPanGestureRecognizer) {
         guard let piece = pan.view else { return }
         let translation = pan.translation(in: piece.superview)
         
         switch pan.state {
         case .began, .changed:
             piece.center = CGPoint(x: piece.center.x + translation.x, y: piece.center.y + translation.y)
             pan.setTranslation(.zero, in: piece.superview)
             self.isPinching = true // 复用 isPinching 标志禁止绘制
         case .ended, .cancelled:
             self.isPinching = false
         default:
             break
         }
         self.resetTouchData()
     }
 }

// // MARK: - UIColor Extension for Hex Colors
// extension UIColor {
//     convenience init(hexString: String, alpha: CGFloat = 1.0) {
//         var hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
//         
//         if hexString.hasPrefix("#") {
//             hexString.remove(at: hexString.startIndex)
//         }
//         
//         var rgb: UInt64 = 0
//         Scanner(string: hexString).scanHexInt64(&rgb)
//         
//         let red = CGFloat((rgb & 0xFF0000) >> 16) / 255.0
//         let green = CGFloat((rgb & 0x00FF00) >> 8) / 255.0
//         let blue = CGFloat(rgb & 0x0000FF) / 255.0
//         
//         self.init(red: red, green: green, blue: blue, alpha: alpha)
//     }
// }
